import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import org.newbee.msgpack.coder.MsgpackDecoder;
import org.newbee.msgpack.coder.MsgpackEncoder;
import org.newbee.proto.OrderProtocol;

/**
 * Created by iss on 17/6/2.
 */
public class NettyTestServer {

    public void bind(int port) throws InterruptedException {
        // 配置NIO线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();// 连接线程
        EventLoopGroup workerGroup = new NioEventLoopGroup();// 处理线程组
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.option(ChannelOption.SO_BACKLOG, 1024);

            bootstrap.childHandler(new ChildChannelHandler());
            // 绑定端口，同步等待成功
            System.out.println("绑定端口，同步等待成功");
            ChannelFuture future = bootstrap.bind("127.0.0.1", port).sync();
            // 等待服务端监听端口关闭，等待服务端链路关闭之后main函数才退出
            System.out.println("等待服务端监听端口关闭，等待服务端链路关闭之后main函数才退出");
            future.channel().closeFuture().sync();
            System.out.println("退出");
        } finally {
            // 优雅退出，释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

    private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {


        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
           // ch.pipeline().addLast("decoder",new ProtobufDecoder(User.class));
//            ch.pipeline().addLast(new LineBasedFrameDecoder(4));
//            ch.pipeline().addLast(new StringDecoder(Charset.forName("utf-8")));
//            ch.pipeline().addLast("msgpack decoder",new MsgpackDecoder());
//            ch.pipeline().addLast("msgpack encoder",new MsgpackEncoder());
   //       ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());
            ch.pipeline().addLast(new ProtobufDecoder(OrderProtocol.Order.getDefaultInstance()));
            ch.pipeline().addLast(new ProtobufEncoder());
            ch.pipeline().addLast(new NettyTestServerHandler2());
        }

    }

    public static void main(String[] args) throws InterruptedException {
        int port = 8888;
        if (args != null && args.length > 0) {
            port = Integer.parseInt(args[0]);
        }
        new NettyTestServer().bind(port);

    }

}
